package com.example.wxy.bbtapp.Service;

import android.util.Log;


import com.example.wxy.bbtapp.Common.BitmapCompare;
import com.example.wxy.bbtapp.Common.HttpHelper;
import com.example.wxy.bbtapp.Startup.AppSettings;
import com.example.wxy.bbtapp.Startup.DbService;
import com.example.wxy.bbtapp.Common.FileHelper;
import com.example.wxy.bbtapp.Models.ClassTime;
import com.example.wxy.bbtapp.Models.CourseRecord.ProcessRecord;
import com.example.wxy.bbtapp.Models.CourseRecord.ScreenshotRecord;
import com.example.wxy.bbtapp.Models.RetrunValue.ResultData;
import com.example.wxy.bbtapp.myApplication;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.example.wxy.bbtapp.Common.httpCallBack;
import com.example.wxy.bbtapp.Models.CourseRecord.CourseRecord;

/**
 * Created by yons on 2017/9/9.
 */

public class CourseRecordService {

    public static void PostDB()
    {
        try
        {
           final List<CourseRecord> crs =  DbService.getDB().selector(CourseRecord.class).findAll();
            for(int i=0; i< crs.size(); i++)
            {
                List<ProcessRecord> prs = DbService.getDB().selector(ProcessRecord.class).where("course_record_id","=",crs.get(i).ID).findAll();
                List<ScreenshotRecord> srs = DbService.getDB().selector(ScreenshotRecord.class).where("CourseRecordID","=",crs.get(i).ID).findAll();

                crs.get(i).setProcessRecords(prs);
                crs.get(i).setScreenRecords(srs);
            }

            if(crs.size() ==0)
            {
                Log.d(AppSettings.DebugTag, "CourseRecordService PostDB havnt any records " );
                return;
            }

            checkTokenAndPost(crs, new httpCallBack<ResultData<String>>("提交课堂记录"){
                @Override
                public void onSuccess(ResultData<String> result) {
                    // 删除数据

                    for(int i=0; i< crs.size(); i++)
                    {
                        for (int j=0; j< crs.get(i).getScreenRecords().size(); j++)
                        {
                            Log.v(AppSettings.DebugTag, " CourseRecord uploaded now delete file :" +crs.get(i).getScreenRecords().get(j).getFilePath() );
                            FileHelper.delete(crs.get(i).getScreenRecords().get(j).getFilePath());
                        }
                    }

                    Delete(crs);
                }
            });
        }
        catch (Exception e)
        {

        }
    }

    public static List<ScreenshotRecord> ComparePic(List<ScreenshotRecord> list)
    {
        // 循环图片进行对比
        ScreenshotRecord last = null;
        int index = 0;

        Iterator<ScreenshotRecord> iterator = list.iterator();
        while (iterator.hasNext()) {
            ScreenshotRecord i = iterator.next();

            if (index == 0) {
                // 文件不存在就先不对比
                if (FileHelper.fileIsExists(i.getFilePath()))
                    last = i;
                else
                    continue;
            } else {
                // 把相似度大于80%的去掉
                if (BitmapCompare.similarity(last.getFilePath(), i.getFilePath()) > 0.80f) {
                    FileHelper.delete(i.getFilePath());
                    Log.v(AppSettings.DebugTag,"BitmapCompare > 80% delete file:" + i.getFilePath());
                    iterator.remove();
                    //Current_CourseRecord.getScreenRecords().remove(i);
                } else {
                    last = i;
                }
            }
            index++;
        }
        return list;
    }

    public static List<ScreenshotRecord> GetValidPic(List<ScreenshotRecord> list)
    {
        List<ScreenshotRecord> lsResult = new ArrayList<>();
        try
        {
            Log.d(AppSettings.DebugTag, " GetValidPic ");
            // 大于5张的话把张一张去掉取5张
            if (list.size() <= 5) {
                return list;
            }

            int c = list.size() / 5;
            for (int i = 1; i <= 5; i++)
            {
                lsResult.add(list.get(i * c - 1));
                list.remove(i * c - 1);
            }

            // 删除多的图
            for(int j=0; j<list.size();j++)
            {
                Log.v(AppSettings.DebugTag,"GetValidPic delete unUseless file:" + list.get(j).getFilePath());
                FileHelper.delete(list.get(j).getFilePath());
            }
        }
        catch (Exception e)
        {

        }

        return lsResult;
    }

    public static void checkTokenAndPost(final List<CourseRecord> crs,final httpCallBack<ResultData<String>> callBack)
    {
        HttpHelper.checkTokenOut(new HttpHelper.checkTokenOutCallBack() {
            @Override
            public void callback() {
                Post(crs, callBack);
            }
        });
    }

    public static void Post(List<CourseRecord> crs,final httpCallBack<ResultData<String>> callBack)
    {
        RequestParams params = new RequestParams(myApplication.bindinofs.getServerUrl()+"RestApi/CCAppRecord/BatchSave");

        try
        {
            params.addHeader("Authorization", myApplication.Token);
            JSONArray arr = new JSONArray();
            for(int i=0; i< crs.size(); i++)
            {
                CourseRecord cr = crs.get(i);
                JSONObject js_request = new JSONObject();//服务器需要传参的json对象
                js_request.put("SchoolID", cr.getSchoolID());
                js_request.put("TerminalID", cr.getDeviceID());
                js_request.put("ClassRoomID", cr.getClassRoomID());
                js_request.put("UseDate", cr.getUseDate());//没做
                js_request.put("WeekIndex",cr.getWeekIndex());
                js_request.put("CourseIndex", cr.getCourseIndex());
                js_request.put("EffectiveHours", cr.getEffectiveHours()/60);
                js_request.put("CStatus", cr.getCStatus());
                js_request.put("DeviceID", cr.getDeviceID());
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                js_request.put("LoginTime", df.format(cr.getBeginTime()) );
                js_request.put("LogoutTime", df.format(cr.getEndTime()));

                js_request.put("SubmitDate", df.format(new Date()));

                js_request.put("ScreenList", getScreenShot(cr));
                js_request.put("ProcessList", getProcessList(cr));
                arr.put(js_request);
            }

            params.setAsJsonContent(true);
            params.setBodyContent(arr.toString());
            Log.d(AppSettings.DebugTag, "CousreRecord begin Upload " );
            x.http().post(params,new httpCallBack<String>("提交课堂记录"){
                @Override
                public void onSuccess(String result) {
                    Log.d(AppSettings.DebugTag, "CousreRecord Upload Complite " );
                    ResultData<String> value = ResultData.fromJson(result, String.class);

                    if(value.isSuccess())
                    {
                        if(callBack!=null)
                            callBack.onSuccess(value);
                    }
                }
            });
        }
        catch (JSONException e)
        {

        }
    }

    // 提交
    public static void Post(CourseRecord cr)
    {
        List<CourseRecord> crs = new ArrayList<>();
        crs.add(cr);
        Post(crs, null);
    }

    // 设置 截屏提交参数
    public static JSONArray getScreenShot(CourseRecord cr) {
        JSONArray values = new JSONArray();
        try {
            for (ScreenshotRecord sr : cr.getScreenRecords()) {
                String bitStr = FileHelper.encodeBase64File(sr.getFilePath());
                if(bitStr.length() == 0)
                    continue;
                JSONObject obj = new JSONObject();
                obj.put("Remark", sr.getRemark());
                obj.put("FileName", sr.getFileName());
                obj.put("ScreenTime", sr.getScreenTime());
                obj.put("Imageurl", bitStr );

                values.put(obj);
            }
        } catch (JSONException e) {

        }
        return values;
    }

    // 设置进程提交参数
    public static JSONArray getProcessList(CourseRecord cr)
    {
        JSONArray values = new JSONArray();
        try
        {
            for(ProcessRecord pr : cr.getProcessRecords())
            {
                JSONObject obj = new JSONObject();
                obj.put("ProcessName", pr.whitelist_id);
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                obj.put("UseDate", df.format(cr.getBeginTime()));
                obj.put("UseHours", pr.user_date_secoend / 60);

                values.put(obj);
            }
        }
        catch (JSONException e)
        {

        }
        return values;

    }

    // 建新记录
    public  static CourseRecord NewRecord(ClassTime ct) {
        // 设置当前课程
        CourseRecord Current_CourseRecord = new CourseRecord();

        Current_CourseRecord.setCourseIndex(ct.getCourseIndex());
        Current_CourseRecord.setSchoolID(myApplication.bindinofs.getSchoolID());
        Current_CourseRecord.setDeviceID(myApplication.bindinofs.getDeviceID());
        Current_CourseRecord.setClassRoomID(myApplication.bindinofs.getClassID());

        final Calendar c = Calendar.getInstance();
        Current_CourseRecord.setWeekIndex(c.get(Calendar.DAY_OF_WEEK) - 1);// 周几

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        DateFormat cd = new SimpleDateFormat("yyyy-MM-dd");

        Current_CourseRecord.setUseDate(cd.format(new Date()));

        Current_CourseRecord.setEffectiveHours(AppSettings.MonitorSecond);

        try {
            Current_CourseRecord.setBeginTime(df.parse(cd.format(new Date()) + " " + ct.getStartTime()));
            Current_CourseRecord.setEndTime(df.parse(cd.format(new Date()) + " " + ct.getEndTime()));
        } catch (Exception e) {

        }
        return Current_CourseRecord;
    }

    // 删除数据
    public  static void Delete(List<CourseRecord> crs)
    {
        try
        {
            for(int i=0; i< crs.size(); i++)
            {
                DbService.getDB().delete(crs.get(i));
                DbService.getDB().delete(ProcessRecord.class, WhereBuilder.b("course_record_id", "=", crs.get(i).getID()));
                DbService.getDB().delete(ScreenshotRecord.class, WhereBuilder.b("CourseRecordID", "=", crs.get(i).getID()));
            }

            Log.d(AppSettings.DebugTag, "CousreRecord Delete " );
        }
        catch (Exception e)
        {

        }
    }

    // 保存数据库
    public static void SaveDB(CourseRecord cr)
    {
        try
        {
            DbService.getDB().saveBindingId(cr);

            for(int i=0; i< cr.getProcessRecords().size();i++)
            {
                cr.getProcessRecords().get(i).course_record_id = cr.getID();
                DbService.getDB().saveBindingId(cr.getProcessRecords().get(i));
            }
            for(int i=0; i< cr.getScreenRecords().size();i++)
            {
                cr.getScreenRecords().get(i).setCourseRecordID(cr.getID());
                DbService.getDB().saveBindingId(cr.getScreenRecords().get(i));
            }
            Log.d(AppSettings.DebugTag, "CousreRecord SaveDB" );
        }
        catch (Exception e)
        {
            Log.d(AppSettings.DebugTag, "CousreRecord Save Error" );
        }

    }
}
